// 拦截XMLHttpRequest
(function() {
  const originalOpen = XMLHttpRequest.prototype.open;
  const originalSend = XMLHttpRequest.prototype.send;
  
  XMLHttpRequest.prototype.open = function(method, url) {
    this._method = method;
    this._url = url;
    return originalOpen.apply(this, arguments);
  };
  
  XMLHttpRequest.prototype.send = function(body) {
    const xhr = this;
    this._requestBody = body;
    
    // 检查是否是搜索API请求
    if (
      xhr._url.includes("/api/sns/web/v1/search/notes") ||
      xhr._url.includes("/web/search/notes")
    ) {
      this.addEventListener("load", function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
          try {
            const response = JSON.parse(xhr.responseText);
            
            // 提取URL参数
            const urlObj = new URL(xhr._url, window.location.origin);
            let query = "unknown_query";
            
            // 如果是POST请求，尝试从请求体获取keyword
            if (xhr._method.toUpperCase() === "POST" && xhr._requestBody) {
              try {
                const requestData = JSON.parse(xhr._requestBody);
                if (requestData.keyword) {
                  query = requestData.keyword;
                }
              } catch (e) {
                console.error("Error parsing request body:", e);
              }
            }
            
            console.log("xhr._url", xhr._url, xhr);
            console.log("urlObj", urlObj);
            console.log("query", query);
            console.log("xhr._method", xhr._method);
            console.log("xhr._requestBody", xhr._requestBody);
            
            // 将数据发送到content script
            window.postMessage({
              type: "XIAOHONGSHU_SEARCH_DATA",
              query: query,
              responseData: response,
              url: window.location.href,
              timestamp: new Date().toISOString()
            }, "*");
          } catch (e) {
            console.error("Error processing search response:", e);
          }
        }
      });
    }
    
    return originalSend.apply(this, arguments);
  };
  
  console.log("XMLHttpRequest intercept initialized");
})(); 